<%--
  @author Duminda Dharmakeerthi
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<script src="${pageContext.request.contextPath}/js/landRegistration/longTermLease.js" type="text/javascript"></script>
<script type="text/javascript ">
$(document).ready(function() {
    hideForm();
    $('.cancel').val($('#cancel').val());
});

$(function() {
    $('#nominatedSuccessor').hide();
    $('#deed-tree').treegrid({
        title:$('#longTermLeaseHistory').val(),
        nowrap: false,
        rownumbers: true,
        animate:true,
        collapsible:true,
        idField:'deed',
        treeField:'deed',
        frozenColumns:[
            [
                {title:$('#leaseHistory').val(),field:'deed',width:172,
                    formatter:function(value) {
                        return '<span style="color:red">' + value + '</span>';
                    }
                }
            ]
        ],
        columns:[
            [
                //                    {field:'sublease',title:'Sub-Lease',width:62},
                {field:'name',title:$('#reference').val(),width:415},
                {field:'transfer',title:$('#transfer').val(),width:70},
                {field:'sublease',title:$('#subLease').val(),width:70}
            ]
        ]
    });
    loadAlienationTree();
});
function validateLeasePeriod() {
    //leaseDate
    //alert($("#calculateLeaseDate").val());
    var calculateLaseDate = $("#calculateLeaseDate").val();


    var dt = calculateLaseDate.substring(8, 10);
    var mon = calculateLaseDate.substring(5, 7);
    var yr = calculateLaseDate.substring(0, 4);

    temp1 = mon + "/" + dt + "/" + yr;
    var dateData = Date.parse(temp1);
    var leaseDate = new Date(dateData);

    // alert(leaseDate);

    //subLease Date
    //alert($("#leasePeriod").val());
    //alert($("#issueDate").val());
    var issueDate = $("#issueDate").val();
    var leasePeriod = $("#leasePeriod").val();


    /*var mon = issueDate.substring(0, 2);
     var dt = issueDate.substring(3, 5);
     var yr = issueDate.substring(6, 10);*/

    var dt = issueDate.substring(8, 10);
    var mon = issueDate.substring(5, 7);
    var yr = issueDate.substring(0, 4);

    temp = mon + "/" + dt + "/" + yr;
    var dateData = Date.parse(temp);
    var subLeaseDate = new Date(dateData);
    subLeaseDate.setDate(subLeaseDate.getDate() + 365 * parseInt(leasePeriod));
    //alert(subLeaseDate);


    /*if (leaseDate > subLeaseDate) {
     alert("Success");
     }
     else {
     alert("Error");
     }*/

    jQuery.validator.addMethod("subLeaseValidate", function(element) {
        var result = true;

        if (leaseDate >= subLeaseDate) {
            result = true;
        }
        else {
            result = false;
        }  //alert(result);
        return  result;
    }, "sublease ");

}
function validateTest(type) {
    if (type == 'transfer') {
        $("#land-transfer").validate({
            invalidHandler: function(form, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    var invalidPanels = $(validator.invalidElements()).closest(".ui-tabs-panel", form);
                    if (invalidPanels.size() > 0) {
                        $.each($.unique(invalidPanels.get()), function() {
                            $(this).siblings(".ui-tabs-nav")
                                    .find("a[href='#" + this.id + "']").parent().not(".ui-tabs-selected")
                                    .addClass("ui-state-error")
                                    .show("pulsate", {times: 3});
                        });
                    }
                }
            },
            unhighlight: function(element, errorClass, validClass) {
                $(element).removeClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
                var $panel = $(element).closest(".ui-tabs-panel", element.form);
                if ($panel.size() > 0) {
                    if ($panel.find("." + errorClass + ":visible").size() == 0) {
                        $panel.siblings(".ui-tabs-nav").find("a[href='#" + $panel[0].id + "']")
                                .parent().removeClass("ui-state-error");
                    }
                }
            }
        });
        $("#mortgagePeriodInYears").rules("add", {digits:true, messages:{
            required:$('#pls_enter_valid_no').val()}
        });
        $("#mortgagePeriodInMonths").rules("add", {digits:true, messages:{
            required:$('#pls_enter_valid_no').val()}
        });
        $("#name").rules("add", {required:true, messages:{
            required:$('#this_field_required').val()}
        }); //TODO: name of the holder need to be renamed. Dont use term "name"
        $("#nic").rules("add", {NICNo:true, messages:{
            required:$('#pls_enter_valid_nic_no').val()}
        });
        $("#mobile").rules("add", {phoneNo:true, messages:{
            required:$('#pls_enter_valid_phone_no').val()}
        });
        $("#landPhone").rules("add", {phoneNo:true, messages:{
            required:$('#pls_enter_valid_phone_no').val()}
        });
        $("#email").rules("add", {email:true, messages:{
            required:$('#pls_enter_valid_email').val()}
        });
        $("#fax").rules("add", {phoneNo:true, messages:{
            required:$('#pls_enter_valid_fax_no').val()}
        });
        $("#dateOfBirth").rules("add", {ageValidate:true, messages:{
            required:$('#pls_enter_valid_age').val()}
        });
        $('#startedDate').rules("add", {
            isDateFormated:true,
            isFeatureDate:true,
            messages:{
                ageValidate:$('#pls_enter_valid_age').val()}
        });
    } else if (type == 'subLease') {
        validateLeasePeriod();
        $("#land-sub-lease").validate({
            rules:{
                leasePeriod:{
                    subLeaseValidate: true
                }
            },
            messages:{
                leasePeriod:{
                    subLeaseValidate: "Please enter a Valid Lease Period "
                }
            },
            invalidHandler: function(form, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    var invalidPanels = $(validator.invalidElements()).closest(".ui-tabs-panel", form);
                    if (invalidPanels.size() > 0) {
                        $.each($.unique(invalidPanels.get()), function() {
                            $(this).siblings(".ui-tabs-nav")
                                    .find("a[href='#" + this.id + "']").parent().not(".ui-tabs-selected")
                                    .addClass("ui-state-error")
                                    .show("pulsate", {times: 3});
                        });
                    }
                }
            },
            unhighlight: function(element, errorClass, validClass) {
                $(element).removeClass(errorClass);
                $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
                var $panel = $(element).closest(".ui-tabs-panel", element.form);
                if ($panel.size() > 0) {
                    if ($panel.find("." + errorClass + ":visible").size() == 0) {
                        $panel.siblings(".ui-tabs-nav").find("a[href='#" + $panel[0].id + "']")
                                .parent().removeClass("ui-state-error");
                    }
                }
            }
        });
        $("#referenceNo").rules("add", {required:true, messages:{
            required:$('#pls_enter_reference_no').val()}
        });
        $("#mortgagePeriodInYears").rules("add", {digits:true, messages:{
            required:$('#pls_enter_valid_no').val()}
        });
        $("#mortgagePeriodInMonths").rules("add", {digits:true, messages:{
            required:$('#pls_enter_valid_no').val()}
        });
        $("#name").rules("add", {required:true, messages:{
            required:$('#this_field_required').val()}
        }); //TODO: name of the holder need to be renamed. Dont use term "name"
        $("#nic").rules("add", {NICNo:true, messages:{
            required:$('#pls_enter_valid_nic_no').val()}
        });
        $("#mobile").rules("add", {phoneNo:true, messages:{
            required:$('#pls_enter_valid_phone_no').val()}
        });
        $("#landPhone").rules("add", {phoneNo:true, messages:{
            required:$('#pls_enter_valid_phone_no').val()}
        });
        $("#email").rules("add", {email:true, messages:{
            required:$('#pls_enter_valid_email').val()}
        });
        $("#fax").rules("add", {phoneNo:true, messages:{
            required:$('#pls_enter_valid_fax_no').val()}
        });
        $("#dateOfBirth").rules("add", {ageValidate:true, messages:{
            required:$('#pls_enter_valid_age').val()}
        });
        $('#startedDate').rules("add", {
            isDateFormated:true,
            isFeatureDate:true,
            messages:{
                ageValidate:$('#pls_enter_valid_age').val()}
        });
        $('#issueDate').rules("add", {
            isDateFormated:true,
            isFeatureDate:true,
            messages:{
                ageValidate:$('#pls_enter_valid_age').val()}
        });
    }

}


function loadAlienationTree() {
    var grantId = $('#grantId').attr('value');
    var parent;
    $.getJSON('${pageContext.request.contextPath}/common/AlienationHistoryLookupService', {grantId:grantId}, function(list) {
        var AList = list.alienationList;
        var i = AList.length - 1;
        for (i; i > -1; i--) {
            if (AList[i].immediateParentId == null || AList[i].immediateParentId == 0) {
                parent = null;
            } else {
                // parent = $('#deed-tree').treegrid('find', getImmediateParentId(AList[i]));
                parent = $('#deed-tree').treegrid('find', AList[i].immediateParentId);
            }

            var id = AList[i].id;
            var data = [
                {
                    deed: id,
                    name: AList[i].referenceNo,
                    transfer: '<input type="radio" name="mortgage-transfer" class="transfer" value="Transfer" onclick="transfer(' + id + ')"/>',
                    sublease: '<input type="radio" name="mortgage-transfer" class="sublease" value="SubLease" onclick="sublease(' + id + ')"/>'
                    //                    edit: '<input type="radio" name="edit" class="edit" onclick="loadLandInformationForm(' + id + ')"/>'
                }
            ];
            addAlienation(parent, data);
        }
    });
}
/*
 function getImmediateParentId(obj) {
 var p;
 $.each(obj, function(key, element) {
 if (key == "immediateParent") {
 p = element.id;
 }
 });
 return p;
 }  */

function addAlienation(parent, data) {
    if (parent != null) {
        parent.transfer = '';
        parent.sublease = '';
        $('#deed-tree').treegrid("refresh", parent.deed);
    }
    $('#deed-tree').treegrid('append', {
        parent: (parent ? parent.deed : null),
        data: data
    });
}

function loadLandInformationForm(alienationId) {
    hideForm();
    $('#alienationId').val(alienationId);
    var url = '${"loadDeedInformation.do"}';
    $.get(url, $('#load-form').serialize(), function(data) {
        $("#long-term-lease-update-form").html(data);
    });
}

function mortgage(parent) {
    unSelectEdit();
    $('#mortgage-details').show();
    $('#transfer-details').hide();
    $('.immediateParentId').val(parent);
}
function transfer(parent) {
    unSelectEdit();
    $('#alienationId').val(parent);
    $('#subLeaseOrTransfer').val("transfer");
    var url = '${"loadDeedInformation.do"}';
    $.get(url, $('#load-form').serialize(), function(data) {
        $("#sub-lease-details").html("");
        $("#transfer-details").html(data);
        $('#land-transfer').show();
        $('#land-sub-lease').hide();
        $('#complete-grant-tree').hide();
        $('#tabs').tabs();
        disableLandInformation();
        disableLongTermLeaseInformation();
        $('.immediateParentId').val(parent);
    });
}

function sublease(parent) {
    unSelectEdit();
    $('#alienationId').val(parent);
    $('#subLeaseOrTransfer').val("sublease");
    var url = '${"loadDeedInformation.do"}';
    $.get(url, $('#load-form').serialize(), function(data) {
        $("#transfer-details").html("");
        $("#sub-lease-details").html(data);
        $('#land-sub-lease').show();
        $('#land-transfer').hide();
        $('#complete-grant-tree').hide();
        $('#tabs').tabs();
        disableLandInformation();
        disableForSubLeaseInformation();
        $('.immediateParentId').val(parent);
    });
}

function hideForm() {
    $('#land-transfer').hide();
    $('#land-sub-lease').hide();
    $('#complete-grant-tree').show();
    unSelect();
}

function unSelect() {
    $('.mortgage').attr('checked', false);
    $('.transfer').attr('checked', false);
    //        $('.sublease').attr('checked', false);
}

function unSelectEdit() {
    $('.edit').attr('checked', false);
    $('#long-term-lease-update-form').html('');
}

function remove(deed) {
    var node = $('#deed-tree').treegrid('find', deed);
    $('#deed-tree').treegrid('remove', node.deed);
    unSelect();
    return false;
}

function addRow(tableID) {

    var table = document.getElementById(tableID);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    var cell1 = row.insertCell(0);
    var element1 = document.createElement("input");
    element1.type = "checkbox";
    cell1.appendChild(element1);

    var cell2 = row.insertCell(1);
    cell2.innerHTML = "Name";

    var cell3 = row.insertCell(2);
    var element2 = document.createElement("textarea");
    element2.className = "width-500-px";
    cell3.appendChild(element2);

}

function deleteRow(tableID) {
    try {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;

        for (var i = 0; i < rowCount; i++) {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if (null != chkbox && true == chkbox.checked) {
                table.deleteRow(i);
                rowCount--;
                i--;
            }

        }
    } catch(e) {
        alert(e);
    }
}

function showAmend() {
    $('.amend').show();
}

function hideAmend() {
    $('.amend').hide();
}

function disableLongTermLeaseInformation() {
    var fields = new Array(
            'referenceNo',
            'issueDate',
            'folioNo',
            'folioDate',
            'folioLocation',
            'leasePeriod',
            'lease-diagram-no',
            'permittedLandUsageId',
            'currentLandUsageId',
            'developed-value',
            'commercial-value',
            'undeveloped-value',
            'leaseArrearsFromYear',
            'leaseArrearsToYear',
            'amend-period',
            'ammendYes',
            'ammendNo',
            'alienationComment'
            );
    enableFields(fields);
}

function disableForSubLeaseInformation() {
    var fields = new Array(
            'folioNo',
            'folioDate',
            'folioLocation',
            'lease-diagram-no',
            'permittedLandUsageId',
            'currentLandUsageId',
            'developed-value',
            'commercial-value',
            'undeveloped-value',
            'leaseArrearsFromYear',
            'leaseArrearsToYear',
            'amend-period',
            'ammendYes',
            'ammendNo',
            'alienationComment'
            );
    enableFields(fields);
}

</script>

<div id="init-land-grants-outer" class="form-outer">
    <table id="deed-tree" class="width-100">
        <%-- Deed tree will be here --%>
    </table>
    <s:form method="POST" id="land-transfer" name="init-land-transfer-info">
        <fieldset id="transfer-details">

        </fieldset>
        <hr/>
        <s:hidden name="alienation.id"/>
        <s:hidden name="alienation.holder.id"/>
        <s:hidden name="alienation.holder.contacts.id"/>
        <s:hidden name="alienation.leaseDetail.id"/>

        <div class="form-button-div right-align">
            <s:hidden id="grantId" name="grantId"/>
            <s:hidden id="immediateParentId" cssClass="immediateParentId" name="immediateParentId"/>
            <s:hidden name="deedTree" value="true"/>
            <s:hidden name="updateMode"/>
            <s:hidden name="mortgageOrTransfer" value="transfer"/>
                <%--  <s:hidden name="alienation.alienationMethod.id" value="4"/>
      <s:submit action="addInitialLandInformation" value="%{getText('save.label')}"
                onclick="validateTest('transfer')"/>--%>
            <s:hidden name="alienationType" value="4"/>
            <s:submit action="saveInitialLandInformation" value="%{getText('save.label')}"
                      onclick="validateTest('transfer')"/>
            <input type="button" class="cancel" onclick="hideForm()"/>
            <s:hidden id="cancel" value="%{getText('cancel.label')}"/>
        </div>
    </s:form>
    <s:form method="POST" id="land-sub-lease" name="init-land-sub-lease-info">
        <fieldset id="sub-lease-details">

        </fieldset>
        <hr/>
        <s:hidden name="alienation.id"/>
        <s:hidden name="alienation.holder.id"/>
        <s:hidden name="alienation.holder.contacts.id"/>
        <s:hidden name="alienation.leaseDetail.id"/>

        <div class="form-button-div right-align">
            <s:hidden id="grantId" name="grantId"/>
            <s:hidden id="immediateParentId" cssClass="immediateParentId" name="immediateParentId"/>
            <s:hidden name="deedTree" value="true"/>
            <s:hidden name="updateMode"/>
            <s:hidden name="mortgageOrTransfer" value="sublease"/>
                <%--   <s:hidden name="alienation.alienationMethod.id" value="4"/>
    <s:submit action="addInitialLandInformation" value="%{getText('save.label')}"
                onclick="validateTest('subLease')"/>--%>
            <s:hidden name="alienationType" value="4"/>
            <s:submit action="saveInitialLandInformation" value="%{getText('save.label')}"
                      onclick="validateTest('subLease')"/>
            <input type="button" class="cancel" onclick="hideForm()"/>
            <s:hidden id="cancel" value="%{getText('cancel.label')}"/>
        </div>
    </s:form>
    <div id="long-term-lease-update-form">

    </div>
    <form id="load-form">
        <s:hidden name="alienationId" id="alienationId"/>
        <s:hidden name="mortgageOrTransfer" id="subLeaseOrTransfer"/>
    </form>
</div>
<div id="complete-grant-tree">
    <div class="form-button-div right-align">
        <s:form method="POST" name="complete-grant-tree">
            <s:hidden id="grantId" name="grantId"/>
            <s:submit id="completeGrantTree" action="completeLandInformationTree"
                      value="%{getText('save_and_complete.label')}"/>
        </s:form>
    </div>
</div>
<s:hidden id="longTermLeaseHistory" value="%{getText('long_term_lease_history.label')}"/>
<s:hidden id="leaseHistory" value="%{getText('lease_history.label')}"/>
<s:hidden id="reference" value="%{getText('reference.label')}"/>
<s:hidden id="transfer" value="%{getText('transfer.label')}"/>
<s:hidden id="subLease" value="%{getText('subLease.label')}"/>